

import requests
import hashlib
import time
from urllib.parse import urlencode
from buynewbee import buy
from getpayurl import payurl
import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from sendEmil import send_email
import webbrowser
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor
# 117.72.53.167 administrator Lijin1997!


token = '6253143d-96e3-4efe-a641-f11c80e2edae'
token2 = '6253143d-96e3-4efe-a641-f11c80e2edae'


productids = [
    {'id':'15771','name':'地牛2.0'},
    {'id':'15748','name':'卡布奇诺'},
    {'id':'15781','name':'上上签-钱来'},
    {'id':'15761','name':'天官赐福'},
    {'id':'15293','name':'上上签 发财'},

]

while True:
    # 获取当前时间
    now = datetime.now()
    # 格式化时间为时分秒
    current_time = now.strftime("%H:%M:%S")
    # 打印时分秒
    print("当前时间---------------------------------------------:", current_time)
    # 遍历所有商品ID
    for product_id in productids:
        # time.sleep(0.3)
        times = int(time.time() * 1000)
        # print(f"检查商品 {product_id['name']}")

        params = {
            'order': 'price',
            'page': '1', 
            'per_page': '20',
            'product_id': product_id['id'],  # 使用循环中的product_id
            'sort': 'ASC',
            'timestamp': str(times),
        }

        query_string = 'api/v2/market/productlist?' + urlencode(params) + '&key=6rnrdpjjv6wz2sspxqeibesov1itxddc'
        # print(query_string)
        lowstr = query_string.lower()

        sign = hashlib.md5(lowstr.encode()).hexdigest()
        # print(sign)

        headers = {
            'accept': '*/*',
            'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
            'cache-control': 'no-cache',
            'content-type': 'application/json;charset=UTF-8',
            'origin': 'https://h5.newbee.net.cn',
            'platformn': 'h5',
            'pragma': 'no-cache',
            'priority': 'u=1, i',
            'referer': 'https://h5.newbee.net.cn/',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-site',
            'signature': '2bd17b71495819c32b37b39388bcb2ac',
            'token': token,
            'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1',
            'x-token': sign,
        }

        try:
            response = requests.get('https://api.newbee.net.cn/api/v2/market/productList', params=params, headers=headers)
            list = response.json()['data']['data']


            if len(list) < 4:
                print(f"商品 {product_id['name']} 没有足够的商品信息")
                continue

            print(f"商品: {list[0]['product']['subject']}, 价格: {list[0]['amount']} / {list[1]['amount']} / {list[2]['amount']}")


            # 判断价格差异改为50%
            if float(list[0]['amount']) <= float(list[1]['amount']) * 0.2:
                print('发现低价商品!')
                # 同时锁两个号

                MAX_RETRIES = 10  # 最大重试次数
                retry_count = 0
                flag = True
                while flag and retry_count < MAX_RETRIES:

                    with ThreadPoolExecutor(max_workers=2) as executor:
                        future1 = executor.submit(buy, list[0]['id'], token, product_id['id'])
                        future2 = executor.submit(buy, list[0]['id'], token2, product_id['id'])

                        res = future1.result()
                        res2 = future2.result()


                    print('1res:::',res)
                    print('2res:::',res2)
                    if res['msg'] == 'SUCCESS':
                        flag = False
                    retry_count += 1



                if res['msg'] == 'SUCCESS':
                    time.sleep(1)
                    # 获取支付链接
                    order_id = res['data']['order_id']
                    # 140 121
                    res1 = payurl(order_id,140, token)
                    print('res1:::',res1)
                    # time.sleep(2)
                    if res1['code'] == 1:
                        # 多行文本编辑
                        # 在邮件的content内容里面 加入 商品前五个的信息
                        content = (f'商品: {list[0]["product"]["subject"]}\n'
                                   f'价格: {list[0]["amount"]}\n'
                                   f'商品列表 {list[1]["amount"]}\n'
                                   f'商品列表 {list[2]["amount"]}\n'
                                   f'商品列表 {list[3]["amount"]}\n'
                                   f'type:140 汇付\n'
                                   f'支付链接: {res1["data"]}')

                        send_email('newbee捡漏成功', content)
                        print('https://h5.newbee.net.cn/#/pages/userCenter/orders')
                        url = "https://www.douyin.com/user/self?from_tab_name=main&modal_id=7190605186274954536&showTab=like"
                        webbrowser.open(url)
                        exit()
                    else:
                        res2 = payurl(order_id,121, token)
                        print('res2:::',res2)
                        content2 = (f'商品: {list[0]["product"]["subject"]}\n'
                                   f'价格: {list[0]["amount"]}\n'
                                   f'商品列表 {list[1]["amount"]}\n'
                                   f'商品列表 {list[2]["amount"]}\n'
                                   f'商品列表 {list[3]["amount"]}\n'
                                   f'type:121 易宝\n'
                                   f'支付链接: {res2["data"]}')
                        send_email('newbee捡漏成功',content2)
                        print('https://h5.newbee.net.cn/#/pages/userCenter/orders')
                        url = "https://www.douyin.com/user/self?from_tab_name=main&modal_id=7190605186274954536&showTab=like"
                        webbrowser.open(url)
                        exit()


        except Exception as e:
            print(f'检查商品 {product_id["name"]} 时发生错误:', e)
            continue



